<script setup lang="ts">
import Table from '@/components/table/index.vue';
import useGetList from '@/hooks/useGetList';
import { deleteWxMsg, getWxMsgRecord, GetWxMsgRecordParams, uploadWxMsg } from '@/services/data';
import {
  ElButton, ElForm, ElFormItem, ElInput, ElMessage,
  ElMessageBox, UploadFile, UploadFiles
} from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { getCustomLocalTimeFormat } from 'common/src/utils/time';
import { WxMsgRecord } from 'common/src/apis';
import { toLonLatString } from 'common/src/utils/lnglat';

interface Props {
  visible: boolean;
  active: boolean;
}

interface Emits {
  (e: "update:visible", visible: boolean): void;
}

interface QueryForm {
  name: string;
  content: string;
}

const getListFC = async (params: GetWxMsgRecordParams) => {
  try {
    const res = await getWxMsgRecord(params);
    const { page, length } = params;
    return {
      list: (res.list || []).map((record, idx) => ({
        ...record,
        index: idx + 1 + (page - 1) * length,
      })),
      total: res.total || 0,
      page: params.page || 1,
      size: params.length || 15,
    };
  } catch {
    return {
      list: [],
      total: 0,
      page: 1,
      size: 15,
    };
  }
};

const props = defineProps<Props>();
const emits = defineEmits<Emits>();
const {
  list,
  getList,
  loading,
  total,
  page,
  size,
} = useGetList(getListFC);
const dbFiles = ref<UploadFiles>([]);
const uploadLoading = ref(false);
const form = reactive<QueryForm>({
  name: '',
  content: '',
});
const queryAfterBlur = ref(false);

const handleDeleteRow = async (row: WxMsgRecord) => {
  await ElMessageBox.confirm(`确定删除该条危险报文吗？`, '删除危险报文', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  });
  try {
    await deleteWxMsg(row.id);
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    handleQuery(1, size.value);
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  }
};

const show = computed({
  get() {
    return props.visible;
  },
  set(visible: boolean) {
    emits("update:visible", visible);
  },
});

const columns = [
  {
    prop: 'index',
    label: '序号',
    align: 'center',
    width: 80,
  },
  {
    label: '发布时间',
    align: 'center',
    width: 120,
    render: (columnsProps: { row: WxMsgRecord }) => {
      const { issueTime } = columnsProps.row;
      return h('div', null, getCustomLocalTimeFormat(issueTime, 'YYYY-MM-DD HH:mm:ss'));
    },
  },
  {
    prop: 'name',
    label: '类型名称',
    align: 'center',
    width: 120,
  },
  {
    prop: 'created_time',
    label: '经纬度',
    align: 'center',
    width: 200,
    render: (columnsProps: { row: WxMsgRecord }) => {
      const { area } = columnsProps.row;
      const str = (area || []).reduce((prev, cur, idx) => {
        const { lat, lon } = cur;
        let curStr = prev;
        if (idx > 0){
          curStr += ', ';
        }
        curStr += toLonLatString(lon, lat);
        return curStr;
      }, '');
      return h('div', null, str);
    },
  },
  {
    prop: 'description',
    label: '详情',
    align: 'center',
    render: (columnsProps: { row: WxMsgRecord }) => {
      const { description, weatherContent } = columnsProps.row;
      return h('div', null, [
        h('div', null, description),
        weatherContent ? h('div', null, weatherContent) : undefined,
      ]);
    },
  },
  {
    label: '状态',
    align: 'center',
    width: 80,
    render: (columnsProps: { row: WxMsgRecord }) => {
      const { expireTime } = columnsProps.row;
      const current = new Date().valueOf();
      const invalid = current > expireTime;
      return h('div', {style: {color: invalid ? '#F56C6C' : '#409eff'}}, invalid ? '已过期' : '未过期');
    },
  },
  {
    label: '操作',
    align: 'center',
    width: 80,
    // fixed: 'right',
    renderBtns: [
      { text: '删除', onClick: (_idx: number, row: any) => handleDeleteRow(row), type: 'danger', link: true },
    ]
  },
];

const handleQuery = (page = 1, length = size.value) => {
  queryAfterBlur.value = false;
  // enter会触发input change事件，导致queryAfterBlur变成true，所以这儿加了个setTimeout
  setTimeout(() => {
    queryAfterBlur.value = false;
  }, 0);
  const params: GetWxMsgRecordParams = {
    page,
    length,
  };
  if (form.name.trim()) {
    params.name = form.name.trim();
  }
  if (form.content.trim()) {
    params.content = form.content.trim();
  }
  getList(params);
};

const handleDbFileUpload = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {
  dbFiles.value = uploadFiles;
};

const handleUpload = async () => {
  if (dbFiles.value.length === 0) {
    ElMessage({
      type: 'warning',
      message: '请选择要导入的文件',
    });
    return;
  }
  uploadLoading.value = true;
  try {
    const formData = new FormData();
    dbFiles.value.forEach(file => {
      formData.append('abj', file.raw as any as File);
    })
    await uploadWxMsg(formData);
    ElMessage({
      type: 'success',
      message: '数据导入成功',
    });
    show.value = false;
    handleQuery(1, size.value);
  } catch {
    ElMessage({
      type: 'warning',
      message: '数据导入失败，请重试',
    });
  } finally {
    uploadLoading.value = false;
  }
};

const handleCancelUpload = () => {
  show.value = false;
  dbFiles.value = [];
};

const handleInputBlur = () => {
  if (queryAfterBlur.value) {
    handleQuery();
  }
};

watch(() => props.active, (val) => {
  if (!val) {
    form.name = '';
    form.content = '';
  }
});

onMounted(() => {
  handleQuery(1, size.value);
});
</script>

<template>
  <ElForm v-if="props.active" class="data-query-form" :inline="true" :model="form">
    <ElFormItem>
      <ElInput
        v-model="form.name"
        placeholder="搜索名称"
        clearable
        style="width: 250px;"
        @blur="() => handleInputBlur()"
        @change="queryAfterBlur = true"
        @clear="() => handleQuery()"
        @keydown.enter="() => handleQuery()"
      />
    </ElFormItem>
    <ElFormItem>
      <ElInput
        v-model="form.content"
        placeholder="搜索详情"
        clearable
        style="width: 250px;"
        @blur="() => handleInputBlur()"
        @change="queryAfterBlur = true"
        @clear="() => handleQuery()"
        @keydown.enter="() => handleQuery()"
      />
    </ElFormItem>
  </ElForm>
  <Table
    v-if="props.active"
    :loading="loading"
    :list="list"
    border
    height="calc(100vh - 35px - 62px - 50px - 40px - 60px - 40px)"
    :columns="columns"
    :total="total"
    :page-no="page"
    :page-size="size"
    :get-list="(pageNo: number, pageSize: number) => handleQuery(pageNo, pageSize)"
  />
  <ElDialog
    class="custom-dialog ship-db-upload-dialog"
    v-model="show"
    title="危险报文数据导入"
    width="400"
    align-center
    @close="() => handleCancelUpload()"
    append-to-body
  >
    <ElUpload
      class="ship-db-upload"
      drag
      multiple
      show-file-list
      :auto-upload="false"
      :file-list="dbFiles"
      :limit="10"
      accept=".abj"
      @change="handleDbFileUpload"
    >
      <ElIcon class="el-icon--upload"><UploadFilled /></ElIcon>
      <div class="el-upload__text">
        <em>拖入或点选危险报文(.abj文件)上传</em>
      </div>
    </ElUpload>
    <div class="dialog-footer" style="padding-left: 0;">
      <ElButton class="custom-btn" @click="() => handleCancelUpload()">取消</ElButton>
      <ElButton type="primary" :loading="uploadLoading" @click="() => handleUpload()">确定</ElButton>
    </div>
  </ElDialog>
</template>

<style lang="less" scoped>
</style>
